package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtil {
    // 数据库连接
    private static String URL = null;
    private static String USER = null;
    private static String PASSWORD = null;
    // MariaDB
    private static String DRIVER = null;

    // 静态代码块初始化数据库连接
    static {
        try {
            InputStream dbConfig = JdbcUtil.class.getResourceAsStream("/db.properties");
            Properties properties = new Properties();
            properties.load(dbConfig);
            URL = properties.getProperty("jdbc.URL");
            USER = properties.getProperty("jdbc.UserName");
            PASSWORD = properties.getProperty("jdbc.Password");
            DRIVER = properties.getProperty("jdbc.Driver");
            Class.forName(DRIVER);
        } catch (ClassNotFoundException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 私有化构造方法，防止外部创建对象
    private JdbcUtil() {
    }

    // 获取数据库连接
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
